<template>
	<view class="page">
		<qf-image-cropper
			v-if="showCropper"
			:src="tempFilePathsImages"
			:width="300"
			:height="300"
			zIndex="11"
			@crop="handleCrop"
			@cancel="handleCancel"
		/>
		<!-- 触发按钮 -->
		<view style="width: 100%">
			<view
				class="box_common_5"
				style="flex-wrap: wrap"
			>
				<view
					v-show="fileList1.length > 0"
					v-for="(avatarItem, index) in fileList1"
					:key="index"
					class="margin_right_20 margin_bottom_20"
					style="position: relative"
				>
					<image
						style="width: 150rpx; height: 150rpx"
						:src="avatarItem.url"
						mode="scaleToFill"
					/>
					<view
						@click="deleteImage(index)"
						class="box_common_10 radius_top_right_label"
						style="
							position: absolute;
							top: 0;
							right: 0;
							background: rgba(0, 0, 0, 0.5);
						"
					>
						<image
							style="width: 30rpx; height: 30rpx"
							src="./img/icon_close.png"
						>
					</view>
				</view>
				<view v-show="fileList1.length <= 20" @click="choosePicture">
					<image
						style="width: 150rpx; height: 150rpx"
						src="./img/upload.png"
						mode="scaleToFill"
					/>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import QfImageCropper from '@/components/qf-image-cropper2/components/qf-image-cropper/qf-image-cropper';
export default {
	components: {
		QfImageCropper,
	},
	props: {},
	data() {
		return {
			// 裁剪图片
			showCropper: false, // 是否显示裁剪功能
			tempFilePathsImages: '', // 临时图片路径
			croppedTempFilePathsImages: '', // 裁剪后的图片
		};
	},
	mounted() {},

	methods: {
		// 选择图片
		choosePicture() {
			uni.chooseImage({
				count: 1,
				success: res => {
					this.tempFilePathsImages = res.tempFilePaths[0];
					this.showCropper = true;
				},
			});
		},
		// 删除图片
		deleteImage(index) {
			this[`fileList${1}`].splice(index, 1);
			// 更新 页面图片 updatePhotosList
			this.updatePhotosList();
		},
		// 裁剪完成回调
		async handleCrop(res) {
			this.croppedTempFilePathsImages = res.tempFilePath;
			this.showCropper = false;
			// 可以在这里将裁剪后的图片上传到服务器
			const result = await this.uploadFilePromise(res.tempFilePath);
			this.fileList.push({
				url: result,
			});
			// 更新 页面图片 updatePhotosList
			this.updatePhotosList();
			console.log(result, '裁剪完成');
		},
		// 取消裁剪
		handleCancel(res) {
			if (res) {
				// 用户选择了新图片
				this.tempFilePathsImages = res.file[0].url;
			} else {
				// 用户取消了裁剪
				this.showCropper = false;
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				uni.$u.http
					.upload('/file/test/upload', {
						filePath: url,
						name: 'file',
						timeout: 60000,
					})
					.then(res => {
						resolve(res.data.url);
					})
					.catch(err => {
						reject(err);
					});
			});
		},

		updatePhotosList() {
			this.formData.infoPhotoList = this.fileList.map(item => ({
				photos: item.url,
			}));
		},
	},
};
</script>

<style lang="scss" scoped>
.page {
	background: #f3f5f9;
}
</style>
